/*
 * @Author: gy
 * @Date: 2019-12-17 09:57:18
 * @LastEditors  : gy
 * @LastEditTime : 2020-07-12 21:34:06
 */
import {
    getAction,
    postAction,
    httpAction,
    restFulGetAction,
    downFile
} from "@/api/manage";
import moment from "moment";
export default {
    data() {
        return {
            tableData: [],
            totalCount: 0, // list总条数
            dialogVisible: false, // 新增/编辑弹窗
            detailDialogVisible: false, // 详情弹窗
            checkDialogVisible: false, // 复核弹窗
            action: "add", // 区分新增或编辑动作类型
            selection: [],
            editIndex: 0,
            title: "新增",
            pageNum: 1,
            pageSize: 15,
            loading: false,
            tableRenderFirstTime: true,
            filters: [],
            searchValue: {},
            searchType: ""
        };
    },
    mounted() {
        this.tableRenderFirstTime && this.getList();
    },
    watch: {},
    methods: {
        iPagination(opt) {
            this.pageSize = opt.pageSize;
            this.pageNum = opt.pageNum;
            this.getList();
        },
        filterChange(filters) {
            this.filters = filters;
            this.getList();
        },
        /**
         * @description: 可以获取到comm-table选中项，用来批量删除
         * @param {Array} selection
         * @return:
         */
        selectionChange(selection) {
            console.log(selection, "selectionChange");
            this.selection = selection;
        },
        // 搜索
        async searchForm(val, type) {
            if (
                this.beforeSearchForm &&
                this.$getType(this.beforeSearchForm) == "function"
            ) {
                await this.beforeSearchForm.call(this);
            }
            this.searchType = type;
            this.searchValue = val;
            this.getList();
        },
        // 搜索-重置
        async resetForm(type) {
            if (
                this.beforeResetForm &&
                this.$getType(this.beforeResetForm) == "function"
            ) {
                await this.beforeResetForm.call(this);
            }
            this.searchType = type;
            this.searchValue = {};
            this.getList();
        },
        getList() {
            if (this.url && this.url.list) {
                this.loading = true;
                const params = {};
                for (const item in this.queryConditions) {
                    if (this.queryConditions[item] != null) {
                        params[item] = this.queryConditions[item];
                    }
                }
                this.filters.map(item => {
                    const key = Object.keys(item)[0];
                    if (key) {
                        params[key] = Object.values(item)[0].join(",");
                    }
                });
                // 搜索字段
                if (
                    JSON.stringify(this.searchValue) !== "{}" &&
                    !this.searchType
                ) {
                    params["searchValue"] = JSON.stringify(this.searchValue);
                } else if (
                    JSON.stringify(this.searchValue) !== "{}" &&
                    this.searchType
                ) {
                    for (let k in this.searchValue) {
                        params[k] = this.searchValue[k];
                    }
                } else {
                    delete params["searchValue"];
                }

                httpAction(
                    this.url.list,
                    Object.assign(
                        { pageNum: this.pageNum, pageSize: this.pageSize },
                        params
                    ),
                    this.url.method || "get"
                )
                    .then(res => {
                        this.loading = false;
                        if (res.code === 0) {
                            if (res.total != null) {
                                this.tableData = res.rows || res["data"] || [];
                                this.totalCount = res.total || 0;
                            } else {
                                // 无分页
                                this.tableData = res.rows || res["data"] || [];
                                this.totalCount =
                                    res.rows.length || res["data"].length;
                            }
                        } else {
                            this.$message({ type: "error", message: res.msg });
                        }
                    })
                    .catch(() => {
                        this.loading = false;
                    });
            }
        },
        search() {
            this.getList();
        },
        // 新增/编辑弹窗打开后回调
        dialogOpen() {
            this.$nextTick(() => {});
        },
        // 点击搜索
        handleSearch() {
            this.queryConditions = this.form;
            this.getList();
        },
        // 点击新增
        async handleAdd(data = {}) {
            this.action = "add";
            this.title = "新增";
            this.dialogVisible = true;
            this.$nextTick(async () => {
                this.$refs["addDialog"].$refs["form"].resetFields();
                if (
                    this.beforeAdd &&
                    this.$getType(this.beforeAdd) == "function"
                ) {
                    await this.beforeAdd.call(this, data);
                }
            });
        },
        // 点击编辑
        async handleEdit(data) {
            this.title = "编辑";
            this.action = "edit";

            if (
                this.beforeEdit &&
                this.$getType(this.beforeEdit) == "function"
            ) {
                const res = await this.beforeEdit.call(this, data);
                this.dialogVisible = true;
                this.$nextTick(() => {
                    setTimeout(() => {
                        this.$refs["addDialog"]["form"] = JSON.parse(
                            JSON.stringify(res)
                        );
                    }, 200);
                });
            } else {
                this.dialogVisible = true;
                this.$nextTick(() => {
                    this.$refs["addDialog"]["form"] = Object.assign(
                        {},
                        this.form,
                        data.row
                    );
                });
            }
        },
        // 点击新增/编辑弹窗确认按钮
        async handleConfirm() {
            let param = this.$refs["addDialog"]["form"];

            if (
                this.beforeSubmit &&
                this.$getType(this.beforeSubmit) == "function"
            ) {
                param = await this.beforeSubmit.call(
                    this,
                    JSON.parse(JSON.stringify(param))
                );
            }

            if (param["status"] == -1) {
                return false;
            }

            if (this.action == "add") {
                if (this.url.add) {
                    console.log(this.url.add, "this.url.add");
                    // 如果需要校验
                    if (this.$refs["addDialog"]["rules"]) {
                        let validStatus = await this.$refs["addDialog"][
                            "$refs"
                        ]["form"]
                            .validate()
                            .then(valid => {
                                return new Promise(resolve => {
                                    resolve(valid);
                                });
                            });

                        if (!validStatus) return;
                        // 新增时如果需要检查唯一性
                        let checkRepeatParam = this.$refs["addDialog"][
                            "checkRepeatParam"
                        ];
                        if (checkRepeatParam) {
                            let res = await this.checkRepeatParam(
                                checkRepeatParam,
                                param
                            ); //true 已存在主键数据
                            if (res) return;
                        }
                        console.log(param, "add");
                        httpAction(
                            this.url.add,
                            param,
                            this.url.addMethod || "get"
                        ).then(res => {
                            if (res.code == 0) {
                                this.$message({
                                    type: "success",
                                    message: "新增成功"
                                });
                                this.getList();
                                this.$nextTick(() => {
                                    if (
                                        this.afterSubmit &&
                                        this.$getType(this.afterSubmit) ==
                                            "function"
                                    ) {
                                        this.afterSubmit.call(this, res);
                                    }
                                });
                            } else {
                                this.$message({
                                    type: "error",
                                    message: res.msg
                                });
                                if (
                                    this.afterSubmit &&
                                    this.$getType(this.afterSubmit) ==
                                        "function"
                                ) {
                                    this.afterSubmit.call(this, res);
                                }
                            }
                        });
                    }
                }
            } else if (this.action == "edit") {
                if (this.url.edit) {
                    console.log(param, "edit");
                    httpAction(
                        this.url.edit,
                        param,
                        this.url.editMethod || "get"
                    ).then(res => {
                        if (res.code == "000000") {
                            this.$message({
                                type: "success",
                                message: "编辑成功"
                            });
                            this.getList();
                        } else {
                            this.$message({ type: "error", message: res.msg });
                        }
                    });
                }
            }
            this.dialogVisible = false;
        },
        // 取消
        handleCancel() {
            this.dialogVisible = false;
        },
        handleDetail(param) {
            this.title = "详情";
            this.action = "detail";
            this.detailDialogVisible = true;
            if (this.url.detail) {
                httpAction(
                    this.url.detail,
                    param,
                    this.url.detailMethod || "get"
                ).then(res => {
                    if (res.code == "000000") {
                        this.$refs["detailDialog"]["form"] = res.data;
                    } else {
                        this.$message({ type: "error", message: res.msg });
                    }
                });
            }
        },
        // 点击复核
        handleCheck() {
            this.checkDialogVisible = true;
        },
        // 确认复核
        handleCheckConfirm() {
            this.checkDialogVisible = false;
        },
        /**
         * @description: 批量删除
         * @param {field} 表格column中的字段名
         * @return:
         */
        handleDelete(field) {
            if (!field) return;
            console.log(field, "field");
            if (this.selection.length == 0)
                return this.$message({
                    type: "error",
                    message: "请至少选择一项"
                });
            let fields = this.selection
                .map(item => {
                    console.log(item);
                    return item[field];
                })
                .join(",");
            console.log(fields, "fields");
            if (this.url.delete) {
                restFulGetAction(
                    this.url.delete,
                    { fields },
                    this.url.deleteMethod || "get"
                ).then(res => {
                    if (res.code === 0) {
                        this.$message({
                            type: "success",
                            message: res.msg || "删除成功"
                        });
                        this.getList();
                    } else {
                        this.$message({ type: "error", message: res.msg });
                    }
                });
            }
        },
        // 单个删除
        handleDeleteOne(field) {
            console.log(field);
            if (!field) return;
            if (this.url.delete) {
                restFulGetAction(
                    this.url.delete,
                    field,
                    this.url.deleteMethod || "get"
                ).then(res => {
                    if (res.code === 0) {
                        this.$message({
                            type: "success",
                            message: res.msg || "删除成功"
                        });
                        this.getList();
                    } else {
                        this.$message({ type: "error", message: res.msg });
                    }
                });
            }
        },
        /**
         * @description: 导出
         * @param {type}
         * @return:
         */
        handleExport() {
            if (this.url.export) {
                downFile(this.url.export, this.queryConditions).then(res => {
                    const csvData = new Blob([res], {
                        type: "application/x-xlsx"
                    }); //response.data要导出的内容
                    let mmt = moment().format("YYYYMMDDhhmmss");
                    const file_name = `${mmt}.xlsx`;
                    // for IE
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                        window.navigator.msSaveOrOpenBlob(csvData, file_name);
                    }
                    // for Non-IE (chrome, firefox etc.)
                    else {
                        var a = document.createElement("a");
                        var url = window.URL.createObjectURL(csvData);
                        a.href = url;
                        a.download = file_name;
                        a.click();
                        a.remove();
                        window.URL.revokeObjectURL(url);
                    }
                });
            }
        },
        handleReset() {
            if (this.form) {
                for (let i in this.form) {
                    this.form[i] = "";
                }
            }

            if (this.queryConditions) {
                for (let i in this.queryConditions) {
                    this.queryConditions[i] = "";
                }
            }
        },
        // 自定义索引
        indexMethod(index) {
            if (index < 9) {
                return "0" + (index + 1);
            }
            return index + 1;
        },
        checkRepeatParam(checkRepeatParam, param) {
            return new Promise(resolve => {
                let key = checkRepeatParam["param"];
                let params = new Object();
                params[key] = param[key];
                httpAction(
                    checkRepeatParam.url,
                    params,
                    checkRepeatParam.method || "get"
                ).then(res => {
                    if (res.code == 0) {
                        //1为不唯一 0唯一
                        if (res.data == 1) {
                            this.$message({
                                type: "error",
                                message: "已存在该类型，新增失败"
                            });
                            resolve(true);
                        }
                    } else {
                        this.$message({
                            type: "error",
                            message: res.msg
                        });
                    }
                    resolve(false);
                });
            });
        }
    }
};
